﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Windows;
using System.Windows.Input;
using TestSendTool.Models.BindingModels;
using TestSendTool.Models.EntityModels;

namespace TestSendTool.ViewModels
{
    public class MainViewModel : ViewModelBase
    {
        private MainModel mainModels;

        public MainModel MainModels
        {
            get => mainModels;
            set => Set(ref mainModels, value);
        }

        public ICommand SetCommand
        {
            get { return new RelayCommand<SubItem>(BtnClick); }
        }


        public MainViewModel()
        {
            MainModels = new MainModel();
        }

        private void BtnClick(SubItem subItem)
        {
            #region 确定按钮

            try
            {
                // 解析本地IP和端口
                IPAddress localIp = IPAddress.Parse("192.168.2.30");
                int localPort = int.Parse("6000");

                // 解析目标IP和端口
                IPAddress targetIp = IPAddress.Parse(subItem.IpAdress);
                int targetPort = int.Parse("5000");

                byte[] MessageHeader = new byte[] { 0xCC, 0xFA, 0x00, 0x00 };

                // 获取要发送的报文
                byte[] bytes = BitConverter.GetBytes(subItem.Time);

                // 检查当前系统是否是小端序
                if (BitConverter.IsLittleEndian)
                {
                    Array.Reverse(bytes);
                }

                //添加前缀
                byte[] byteList = MessageHeader.Concat(bytes).ToArray();

                // 创建UDP客户端并绑定本地端点
                using (UdpClient udpClient = new UdpClient(new IPEndPoint(localIp, localPort)))
                {
                    // 设置超时时间（1秒）
                    udpClient.Client.ReceiveTimeout = 1000;

                    // 发送数据到目标端点
                    int bytesSent = udpClient.Send(byteList, byteList.Length, new IPEndPoint(targetIp, targetPort));

                    if (bytesSent != byteList.Length)
                    {
                        MessageBox.Show("发送失败：未发送完整数据", "错误");
                        return;
                    }

                    //等待接收确认
                    try
                    {
                        // 这里假设目标设备会返回一个确认字节
                        IPEndPoint remoteEndPoint = null;
                        byte[] ackBytes = udpClient.Receive(ref remoteEndPoint);

                        if (ackBytes == null || ackBytes.Length == 0)
                        {
                            MessageBox.Show("未收到目标设备的确认响应", "警告");
                        }
                        else
                        {
                            MessageBox.Show("发送成功并收到确认", "成功");
                        }
                    }
                    catch (SocketException ex) when (ex.SocketErrorCode == SocketError.TimedOut)
                    {
                        MessageBox.Show("发送成功，但未收到目标设备的确认响应（超时）", "警告");
                    }
                }
            }
            catch (FormatException ex)
            {
                MessageBox.Show($"格式错误: {ex.Message}", "提示");
            }
            catch (SocketException ex)
            {
                if (ex.SocketErrorCode == SocketError.HostNotFound)
                {
                    MessageBox.Show($"目标主机不存在或不可达: {subItem.IpAdress}", "错误");
                }
                else
                {
                    MessageBox.Show($"网络错误: {ex.Message} (错误代码: {ex.ErrorCode})", "提示");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误: {ex.Message}", "提示");
            }

            #endregion
        }

    }
}
